package org.example.hengshengexam;

import java.util.Scanner;

public class CalculatorWithErrorHandling {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("请输入第一个数字：");
            double num1 = scanner.nextDouble();
            System.out.print("请输入运算符（+、-、*、/）：");
            String operator = scanner.next();
            System.out.print("请输入第二个数字：");
            double num2 = scanner.nextDouble();

            double result = 0;
            switch (operator) {
                case "+":
                    result = num1 + num2;
                    break;
                case "-":
                    result = num1 - num2;
                    break;
                case "*":
                    result = num1 * num2;
                    break;
                case "/":
                    if (num2 == 0) {
                        throw new ArithmeticException("除数不能为0");
                    }
                    result = num1 / num2;
                    break;
                default:
                    throw new IllegalArgumentException("无效的运算符");
            }
            System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
        } catch (ArithmeticException e) {
            System.out.println("算术异常：" + e.getMessage());
        } catch (IllegalArgumentException e) {
            System.out.println("参数异常：" + e.getMessage());
        } catch (java.util.InputMismatchException e) {
            System.out.println("输入异常：请输入有效的数字");
        } finally {
            scanner.close();
        }
    }
}